package com.proton.carepatchtemp.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

import com.apkfuns.logutils.LogUtils;
import com.facebook.CallbackManager;
import com.facebook.FacebookCallback;
import com.facebook.FacebookException;
import com.facebook.GraphRequest;
import com.facebook.login.LoginResult;
import com.facebook.login.widget.LoginButton;
import com.google.android.gms.auth.api.Auth;
import com.google.android.gms.auth.api.signin.GoogleSignInAccount;
import com.google.android.gms.auth.api.signin.GoogleSignInOptions;
import com.google.android.gms.auth.api.signin.GoogleSignInResult;
import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.proton.carepatchtemp.R;
import com.proton.carepatchtemp.base.BaseActivity;
import com.proton.carepatchtemp.constant.Codes;
import com.proton.carepatchtemp.constant.Extras;
import com.proton.carepatchtemp.login.activity.LoginFirstActivity;
import com.proton.carepatchtemp.utils.SpUtils;
import com.proton.carepatchtemp.utils.eventbus.MainEvent;
import com.proton.carepatchtemp.utils.net.SignCenter;
import com.proton.carepatchtemp.utils.ui.ToastUtils;

public class LoginInternationalActivity extends BaseActivity {

    private static final int RC_SIGN_IN = 1;

    private CallbackManager mCallbackManager;

    private Button mBtnLoginGoogle;
    private LoginButton mLoginButtonFacebook;
    /**
     * 切换到卡帕奇体温
     */
    private TextView mTvSwitchEdition;
    private GoogleApiClient mMGoogleApiClient;
    private GoogleSignInOptions mGso;
    private String mFullName;
    private String mEmail;

    @Override
    public void dealEvent(MainEvent event) {
        switch (event.getId()) {
            case Codes.NET_SIGN_LOGIN:
                if (event.isSuccess()) {
                    doLogin();
                } else {
                    Toast.makeText(this, event.getMsg(), Toast.LENGTH_SHORT).show();
                }
                break;
            default:
                break;
        }
    }

    private void doLogin() {
        //Toast.makeText(this,"开始登录",Toast.LENGTH_SHORT).show();
        Intent intent = new Intent(LoginInternationalActivity.this, MainActivity.class);
        startActivity(intent);
        overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        finish();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login_international);

        mGso = new GoogleSignInOptions.Builder(GoogleSignInOptions.DEFAULT_SIGN_IN)
                .requestEmail()
                .requestIdToken("915782849953-dvko1hvf40v70hg6gp637qf2pfrcgd12.apps.googleusercontent.com")
                .build();

        mMGoogleApiClient = new GoogleApiClient.Builder(this)
                .enableAutoManage(this, new GoogleApiClient.OnConnectionFailedListener() {
                    @Override
                    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
                        ToastUtils.e(R.string.string_login_fail);
                    }
                })
                .addApi(Auth.GOOGLE_SIGN_IN_API, mGso)
                .build();

        initView();
        setListener();
    }

    @Override
    protected void setListener() {
        mTvSwitchEdition.setOnClickListener(v -> {
            SpUtils.saveBoolean(Extras.APP_EDITION, false);
            jumpToActivty(LoginFirstActivity.class);
            overridePendingTransition(R.anim.umeng_socialize_fade_in, R.anim.umeng_socialize_fade_out);
            finish();
        });

        mCallbackManager = CallbackManager.Factory.create();
        mLoginButtonFacebook.setReadPermissions("email", "public_profile", "user_friends");
        mLoginButtonFacebook.registerCallback(mCallbackManager, new FacebookCallback<LoginResult>() {
            @Override
            public void onSuccess(LoginResult loginResult) {
                // App code
                LogUtils.d(loginResult);
                GraphRequest request = GraphRequest.newMeRequest(
                        loginResult.getAccessToken(),
                        (object, response) -> {
                            // Application code
                            LogUtils.json(object.toString());
                            SignCenter.loginFacebook(object.optString("email"), object.optString("id"), loginResult.getAccessToken().getToken());
                            LogUtils.d(object.optString("email") + "|" + object.optString("id"));
                        });
                Bundle parameters = new Bundle();
                parameters.putString("fields", "id,name,email,gender,birthday");
                request.setParameters(parameters);
                request.executeAsync();
            }

            @Override
            public void onCancel() {
                // App code
                ToastUtils.i(R.string.string_cancel_login);
            }

            @Override
            public void onError(FacebookException exception) {
                ToastUtils.e(R.string.string_login_fail);
                LogUtils.e(exception);
                // App code
            }
        });

        mBtnLoginGoogle.setOnClickListener(v -> {
            Intent signInIntent = Auth.GoogleSignInApi.getSignInIntent(mMGoogleApiClient);
            startActivityForResult(signInIntent, RC_SIGN_IN);
        });
    }

    @Override
    public void onEventMainThread(MainEvent event) {
        dealOnEvent(event);
    }

    private void initView() {
        mBtnLoginGoogle = findViewById(R.id.btn_login_google);
        mLoginButtonFacebook = findViewById(R.id.login_button_facebook);
        mTvSwitchEdition = findViewById(R.id.tv_switch_edition);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        mCallbackManager.onActivityResult(requestCode, resultCode, data);

        if (requestCode == RC_SIGN_IN) {
            GoogleSignInResult result = Auth.GoogleSignInApi.getSignInResultFromIntent(data);
            if (result.isSuccess()) {
                GoogleSignInAccount acct = result.getSignInAccount();
                LogUtils.d(acct);
                mFullName = acct.getDisplayName();
                mEmail = acct.getEmail();
                LogUtils.d("");
                LogUtils.d(mFullName + "|" + mEmail);
                // Get account information
                SignCenter.loginGoogle(mEmail, acct.getId(), acct.getIdToken());
            } else {
                Toast.makeText(this, R.string.string_login_fail, Toast.LENGTH_SHORT).show();
            }
        }
    }
}
